﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySite.Model;
using MySite.BLL;
using System.Web.SessionState;

namespace MySite.Handler
{
    /// <summary>
    /// Vote 的摘要说明
    /// </summary>
    public class VoteHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json; charset=utf-8";

            switch(context.Request.QueryString["action"])
            {
                case "vote":
                    Vote(context);
                    break;
                default:
                    break;
            }
            
        }

        private void Vote(HttpContext context)
        {
            string[] voteitems = context.Server.UrlDecode(context.Request.QueryString["content"]).Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            int voteid = Convert.ToInt32(context.Request.QueryString["voteid"]);

            VoteInfo voteInfo = new MySite.BLL.Vote().TakeOneByID(voteid);


            try
            {

                foreach (var item in voteitems)
                {
                    VoteItemInfo vii = (from temp in voteInfo.VoteItems where temp.Text == item select temp).FirstOrDefault();
                    vii.VoteCount++;
                    vii.VoteCountPercent = ((decimal)vii.VoteCount) / (from temp in voteInfo.VoteItems select temp.VoteCount).Sum();
                    new VoteItem().UpdateVote(vii);
                }
            }
            catch
            {

            }

            context.Response.Write(string.Format("{{\"code\":{0},\"msg\":\"{1}\"}}",0,"投票成功!"));

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}